<template>
  <main-card-admin title="角色管理" :loading="loading" :main-body-style-obj="{ paddingTop: '32px' }">
    <template #tool-btn>
      <a-button v-if="checkKey('admin-role-manage-add')" type="primary" @click="goAddOrEdit()"> 创建角色</a-button>
    </template>
    <template #screen-space>
      <a-row justify="space-between">
        <a-col class="mr-24">
          <a-select
            ref="select"
            v-model:value="pageForm.status"
            class="w-140"
            :options="statusOptions"
            :field-names="{ label: 'text', value: 'value' }"
            @change="getRoleListData({ offset: 1 })"
          />
        </a-col>
        <a-col>
          <a-input
            v-model:value="pageForm.name"
            v-trim
            class="h-36 w-328"
            allow-clear
            placeholder="请输入角色名"
            @keyup.enter="getRoleListData({ offset: 1 })"
          >
            <template #prefix> <i class="iconfont icon-search-line"></i> </template>
          </a-input>
        </a-col>
      </a-row>
    </template>
    <div class="page">
      <GTable
        :columns="tableColumns"
        :data="userList"
        :page-form="pageForm"
        :loading="loading"
        :action-option="tableActionOption"
        :action-width="170"
        @getDataList="getRoleListData"
        @rowClick="previewRole"
        @change="tableChange"
      >
        <template #time="{ record, column }"> {{ dateFormat(record[column.dataIndex]) }}</template>
        <template #status="{ record }">
          <div :class="['table__status', record.status === '禁用' && 'error']">{{ record.status }}</div>
        </template>
      </GTable>
    </div>
    <template #page-footer> </template>
  </main-card-admin>
  <delete-confirm-dialog
    v-model:show="isDeleteDialogShow"
    :msg="`已有${currentCollection}个人使用此角色，请确认是否删除？`"
    :label="`请输入角色名称`"
    :loading="confirmLoading"
    :confirm-name="currentDeleteTaskItem?.name"
    @ok="onOkDeleteTask"
  />
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import { Modal } from 'ant-design-vue'
  import { dateFormat } from 'g6-fn'
  import { createVNode, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
  import WarnIcon from '@/components/icon/IconWarning/index.vue'
  import MainCardAdmin from '@/components/MainCardAdmin/index.vue'
  import { checkKey } from '@/directives/auth'
  import useList from '@/hooks/use-list'
  import { roleApi } from '@/services/api'

  import { RoleDetail } from '../types'

  interface IUser {
    description: string
    id: string
    createTime: string
    updateTime: string
    name: string
    status: string
    isAdmin: string
    roleIds: null
    roleNames: string
  }

  interface PageForm {
    name: string
    status: string | number
    columns: 'createTime' | 'updateTime' | ''
    order: 'desc' | 'asc'
  }

  const tableColumns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      width: 160
    },
    {
      title: '教师用户',
      dataIndex: 'userNames',
      minWidth: 100
    }
    // {
    //   title: '角色权限',
    //   slot: 'status',
    //   dataIndex: 'status',
    //   width: 100
    // },
    // {
    //   title: '更新时间',
    //   dataIndex: 'updateTime',
    //   slot: 'time',
    //   isSort: true,
    //   width: 190
    // },
    // {
    //   title: '创建时间',
    //   dataIndex: 'createTime',
    //   slot: 'time',
    //   isSort: true,
    //   width: 190
    // },
  ]

  // 状态筛选
  const statusOptions = [
    {
      text: '全部状态',
      value: ''
    },
    {
      text: '可用',
      value: 1
    },
    {
      text: '禁用',
      value: 0
    }
  ]

  const router = useRouter()

  const tableActionOption = {
    // 判断是什么类型的列表，来展示不同的操作按钮
    list: [
      {
        auth: 'admin-role-manage-edit',
        text: '编辑',
        onClick: (record: IUser) => handleRole(record.id, 'update')
      },
      // {
      //   auth: 'admin-user-manage-admin-disable',
      //   dynamicText: (record: IUser) => (record.status === '可用' ? '禁用' : '启用'),
      //   onClick: (record: IUser) => handleRole(record.id, record.status === '可用' ? 'disabled' : 'open')
      // },
      {
        auth: 'admin-user-manage-admin-edit',
        text: '删除',
        onClick: (record: IUser) => handleDelete(record as IUser)
      }
    ]
  }
  const {
    pageForm,
    dataList: userList,
    getDataList: getRoleListData,
    loading
  } = useList<PageForm, IUser>(roleApi.list, {
    name: '',
    status: '',
    columns: '',
    order: 'desc'
  })

  const tableChange = (pagination: any, filters: any, sorter: any) => {
    pageForm.value.columns = sorter.field
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    if (!sorter.order) {
      pageForm.value.columns = 'updateTime'
      pageForm.value.order = 'desc'
    }
    getRoleListData({ offset: 1 })
  }

  const goAddOrEdit = (id?: string) => {
    if (!id) {
      router.push(`/role-manage/add`)
      return
    }
    router.push(`/role-manage/edit/${id}`)
  }

  const handleRole = (id: string, status: 'disabled' | 'open' | 'update') => {
    if (status === 'update') {
      goAddOrEdit(id)
      return
    }

    interface Item {
      api: any
      text: string
      des: string
      params?: any
    }

    const statusOptions: Record<'disabled' | 'open', Item> = {
      disabled: {
        api: roleApi.disable,
        text: '禁用',
        des: '此角色将被禁用，请确认操作',
        params: {
          id,
          status: 0
        }
      },
      open: {
        api: roleApi.enable,
        text: '启用',
        des: '此角色将被启用，请确认操作',
        params: {
          id,
          status: 1
        }
      }
    }

    const handleItem = statusOptions[status]

    Modal.confirm({
      title: `确定${handleItem.text}？`,
      icon: createVNode(WarnIcon),
      content: handleItem.des,
      okText: handleItem.text,
      cancelText: '取消',
      centered: true,
      onOk: async () => {
        const res = await handleItem.api(handleItem.params)
        if (res.code === 'SYSTEM-100000') {
          message.success(`该角色已${handleItem.text}`)
          getRoleListData()
        }
      }
    })
  }
  //删除
  const currentDeleteTaskItem = ref<IUser>()
  const isDeleteDialogShow = ref(false)
  const handleDelete = (item: IUser) => {
    currentDeleteTaskItem.value = item
    getUserRun(item.id)
    isDeleteDialogShow.value = true
  }
  //查询案例收藏人数
  const currentCollection = ref(0)
  const { runAsync: getUserRun } = useRequest<ResponseData<number>>((id: string) => roleApi.getBindingNum(id)(), {
    onSuccess: ({ data }) => {
      currentCollection.value = data
    }
  })
  const { loading: confirmLoading, runAsync: runDelRole } = useRequest(roleApi.del)
  const onOkDeleteTask = async () => {
    await runDelRole({}, { urlParams: { id: currentDeleteTaskItem.value?.id || '' } })
    message.success('该角色已删除')
    isDeleteDialogShow.value = false
    getRoleListData()
  }

  const previewRole = (record: RoleDetail) => {
    router.push(`/role-manage/detail/${record.id}`)
  }

  getRoleListData()
</script>

<style lang="less" scoped>
  @import '@/styles/mixins.less';

  .view-info {
    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;

      span:nth-of-type(1) {
        .font14b();
      }

      span:nth-of-type(2) {
        .font14();
      }
    }

    & > * + * {
      margin-top: 16px;
    }
  }
</style>
